package org.example;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.WritableImage;
import javafx.scene.web.WebView;
import javafx.concurrent.Worker;
import netscape.javascript.JSObject;
import tech.tablesaw.plotly.Plot;
import tech.tablesaw.plotly.components.Figure;
import tech.tablesaw.plotly.components.Page;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

public class ReliableFigureToImageConverter {

    public static boolean convertToImage(Figure figure, File outputFile,
                                         int width, int height, String format)
            throws InterruptedException {

        // 初始化JavaFX平台
        if (!Platform.isFxApplicationThread()) {
            CountDownLatch initLatch = new CountDownLatch(1);
            Platform.startup(initLatch::countDown);
            initLatch.await();
        }

        // 创建临时HTML文件
        File tempHtml = createTempHtml(figure);
        if (tempHtml == null) return false;

        CountDownLatch latch = new CountDownLatch(1);
        AtomicBoolean success = new AtomicBoolean(false);

        Platform.runLater(() -> {
            WebView webView = new WebView();
            webView.setPrefSize(width, height);

            // 关键修改1：启用JavaScript
            webView.getEngine().setJavaScriptEnabled(true);

            // 关键修改2：添加加载完成监听器
            webView.getEngine().getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {
                if (newState == Worker.State.SUCCEEDED) {
                    // 关键修改3：使用JavaScript确认图表渲染完成
                    webView.getEngine().executeScript(
                            "window.setTimeout(function() {" +
                                    "   var promise = Plotly.d3.select('.plotly-graph-div').data()[0]._fullLayout._redrawPromise;" +
                                    "   promise.then(function() {" +
                                    "       window.java.renderingComplete();" +
                                    "   });" +
                                    "}, 500);"); // 初始延迟500ms
                }
            });

            // 关键修改4：暴露Java回调接口
            webView.getEngine().setCreatePopupHandler(config -> {
                webView.getEngine().executeScript("window.java = {"
                        + "renderingComplete: function() {"
                        + "    window.javaBridge.renderingComplete();"
                        + "}};");
                return null;
            });

            // 关键修改5：添加JS到Java的桥接
            JSObject window = (JSObject) webView.getEngine().executeScript("window");
            window.setMember("javaBridge", new JavaBridge(() -> {
                try {
                    // 关键修改6：使用像素检查确保不是空白图片
                    WritableImage image = new WritableImage(width, height);
                    webView.snapshot(null, image);

                    // 检查中心区域是否非白色
//                    if (!isImageBlank(image)) {
                        ImageIO.write(SwingFXUtils.fromFXImage(image, null), format, outputFile);
                        success.set(true);
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown();
                    tempHtml.delete();
                }
            }));

            try {
                webView.getEngine().load(tempHtml.toURI().toURL().toExternalForm());
            } catch (Exception e) {
                e.printStackTrace();
                latch.countDown();
            }
        });

        latch.await();
        return success.get();
    }

    // 辅助类：JavaScript到Java的桥接
    public static class JavaBridge {
        private final Runnable callback;

        public JavaBridge(Runnable callback) {
            this.callback = callback;
        }

        public void renderingComplete() {
            callback.run();
        }
    }



    private static File createTempHtml(Figure figure) {
        try {
            File tempFile = File.createTempFile("tablesaw-", ".html");
            tempFile.deleteOnExit();

            // 关键修改7：在HTML中添加Plotly渲染完成检测
            String originalHtml = write(figure);
            String modifiedHtml = originalHtml.replace("</body>",
                    "<script>" +
                            "document.addEventListener('DOMContentLoaded', function() {" +
                            "   if (typeof Plotly !== 'undefined') {" +
                            "       Plotly.d3.select('.plotly-graph-div').data()[0]._fullLayout._redrawPromise.then(function() {" +
                            "           if (window.java && window.java.renderingComplete) {" +
                            "               window.java.renderingComplete();" +
                            "           }" +
                            "       });" +
                            "   }" +
                            "});" +
                            "</script></body>");

            Files.write(tempFile.toPath(), modifiedHtml.getBytes());
            return tempFile;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }



    protected static final String DEFAULT_DIV_NAME = "target";


    public static String write(Figure figure) {
        return write(figure, DEFAULT_DIV_NAME);
    }


    public static String write(Figure figure, String divName) {
        Page page = Page.pageBuilder(figure, divName).plotlyJsLocation("./plotly-latest.min.js").build();
        String output = page.asJavascript();
        return output;
    }



    public static void main(String[] args) throws Exception {
//
//        Figure[] charts = IMRControlChart.getChats(new String[]{});
//        // 示例: 创建一个简单的图表
//        Figure figure = charts[0];// 你的Figure创建代码
//
//        try {
//            boolean success = convertToImage(
//                    figure,
//                    new File("output.png"),
//                    800,
//                    600,
//                    "png"
//            );
//
//            if (success) {
//                System.out.println("图片转换成功!");
//            } else {
//                System.out.println("图片转换失败!");
//            }
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } finally {
//            // 退出JavaFX平台
//            Platform.exit();
//        }
    }

}